package com.brillilab.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.util.Properties;


/**
 * @author LJ
 * @ClassName: EmailSendUtil
 * @Description: 邮件发送 Util
 * @date 2017年12月20日 下午3:26:33
 */
@Slf4j
public class EmailSendUtil {

    // 设置服务器
    private String valueSmtp;
    private String valuePort;
    // 发件人用户名、密码
    private String sendUser;
    private String sendPwd;
    //发件人署名
    private String sendUserName;
    // 建立会话
    private MimeMessage message;
    private Session session;


    /**
     * 邮箱发送 初始化方法
     *
     * @param valueSmtp 设置服务器VALUE (smtp.163.com)
     * @param sendUser  发件人用户名 (lijian541x@163.com)
     * @param sendPwd   密码 (*****)
     */
    public EmailSendUtil(String valueSmtp, String port, String sendUser, String sendPwd, String sendUserName) {

        this.valueSmtp = valueSmtp;
        this.valuePort = port;
        this.sendUser = sendUser;
        this.sendPwd = sendPwd;
        this.sendUserName = sendUserName;

        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", this.valueSmtp);
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", this.valuePort);
        props.setProperty("mail.smtp.socketFactory.port", this.valuePort);

        session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EmailSendUtil.this.sendUser, EmailSendUtil.this.sendPwd);
            }
        });
        session.setDebug(true);
        message = new MimeMessage(session);
    }

    /**
     * 发送邮件
     *
     * @param title        邮件主题
     * @param sendHtml     邮件内容
     * @param receiveEmail 收件人邮箱
     */
    public boolean sendHtmlEmail(String title, String sendHtml, String receiveEmail) {
        try {
            log.info("sendEmail","发送邮件标题："+title);
            log.info("sendEmail","发送邮件内容："+sendHtml);
            log.info("sendEmail","邮件接收人："+receiveEmail);
            // 发件人
            InternetAddress from = new InternetAddress(MimeUtility.encodeText(sendUserName) + "<" + sendUser + ">");
            //InternetAddress from = new InternetAddress(sendUser);
            message.setFrom(from);
            // 收件人
            InternetAddress to = new InternetAddress(receiveEmail);
            message.setRecipient(Message.RecipientType.TO, to);
            // 邮件标题
            message.setSubject(title);
            String content = sendHtml.toString();
            // 邮件内容,也可以使纯文本"text/plain"
            message.setContent(content, "text/html;charset=GBK");
            message.saveChanges();
            Transport transport = session.getTransport("smtp");
            // smtp验证，就是你用来发邮件的邮箱用户名密码
            transport.connect(valueSmtp, sendUser, sendPwd);
            // 发送
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            log.info("sendEmail","邮件发送成功");
            return true;
        } catch (Exception e) {
            log.error(">>>>>>   邮件发送异常   " + receiveEmail, e);
            return false;
        }
    }

    /**
     * 获取邮件模板内容
     *
     * @param url 模板url
     * @return
     */
    public String getEmailHtml(InputStream stream) {
        StringBuffer sb = new StringBuffer();
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(stream);
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            String s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s).append("\n");
            }
        } catch (Exception e) {
            log.error("Error occurred, cause by: ", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("Error occurred, cause by: ", e);
                }
            }
        }

        return sb != null ? sb.toString() : "";
    }

    public static void main(String[] args) {
        EmailSendUtil se = new EmailSendUtil("smtp.mxhichina.com", "465", "support@brillilab.com", "Dyy19941005", "布理岚柏售后支持");
//        se.sendHtmlEmail("邮件标题", "邮件内容:</br>床前明月光22</br><a href='https://daohang.qq.com' target='_blank'><img src='http://zxpic.imtt.qq.com/zxpic_imtt/bkt20/2017/12/20/1440/originalimage/144107_2682108866118419723_1_1000_562.jpg'></a>", "895410055@qq.com");
        se.sendHtmlEmail("邮件标题", "邮箱邀请注册:</br>来自【*****的Lab】邀请注册</br>尊敬的  *** 先生/女士您好，*****的Lab  邀请您加入，请点击：<a href='https://www.baidu.com' target='_blank'>******</a>查看。（链接3天后失效，请您尽快完成注册）", "807697701@qq.com");
    }
}
